package com.battle.service.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.dto.role.*;
import com.battle.pojo.entity.Role;
import com.battle.service.mapper.RoleMapper;
import com.battle.service.repository.in.RoleRepository;
import nirvana.core.exceptions.BizException;
import nirvana.core.repository.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：
 * 【环 境】：J2SE
 * 【详 细】：
 *
 */
@Service
public class RoleRepositoryImpl extends Repository<RoleMapper, Role> implements RoleRepository {

    private final RoleMapper mapper;

    public RoleRepositoryImpl(RoleMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public Role createToBefore(Role role) {

        String name = role.getName();

        Role po = null;
        Role byPo = null;


        //校验角色名称，不能重复添加
        po = new Role();
        po.setName(name);

        byPo = getByEntity(po);

        if (byPo != null) {
            throw new BizException("角色名称重复");
        }

        return super.createToBefore(role);
    }


    @Override
    public Role editToBefore(Role role) {

        //原本的角色
        Long id = role.getId();

        String name = role.getName();

        Role po = null;
        Role byPo = null;


        //校验角色名称，不能重复添加
        po = new Role();
        po.setName(name);

        byPo = getByEntity(po);
        if (byPo != null && !byPo.getId().equals(id)) {
            throw new BizException("角色名称重复");
        }


        return super.editToBefore(role);
    }

    /**
     * 系统角色不可手动删除
     *
     * @param id
     * @return
     */
    @Override
    public Role removeToBefore(Serializable id) {
        Role resource = getByIdCheck(id);
        if (resource.getIsSystem()) {
            throw new BizException("系统角色不可手动删除");
        }
        return super.removeToBefore(id);
    }

    /**
     * 搜索角色
     * @param dto
     * @return
     */
    @Override
    public Page<Role> selectRole(SelectRoleDto dto) {

        return mapper.selectRole(dto);
    }

    /**
     * 获取当前用户的全部角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<Role> getRoleListByUserId(Long userId) {
        if (userId == null) {
            return Collections.EMPTY_LIST;
        }
        return mapper.getRoleListByUserId(userId);
    }

    /**
     * 获取这个用户的全部角色id
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> getRoleIdsListByUserId(Long userId) {
        return mapper.getRoleIdsListByUserId(userId);
    }

    /**
     * 获取部门下的全部角色id
     *
     * @param departmentIdList
     * @return
     */
    @Override
    public List<Long> getRoleIdsByDepartmentId(List<Long> departmentIdList) {
        if (CollectionUtils.isEmpty(departmentIdList)) {
            return Collections.EMPTY_LIST;
        }
        List<Long> list = mapper.getRoleIdsByDepartmentId(departmentIdList);
        return list;
    }

    /**
     * 批量删除角色
     *
     * @param idList
     */
    @Override
    public void bathRemoveRole(List<Long> idList) {
        mapper.bathRemoveRole(idList);
    }

    /**
     * 删除部门下的角色
     *
     * @param departmentIds
     */
    @Override
    public void removeRoleByDepartmentIds(List<Long> departmentIds) {
        if (CollectionUtils.isEmpty(departmentIds)) {
            return;
        }
        Role po = new Role();
        po.setIsDelete(Boolean.FALSE);

        QueryWrapper<Role> wrapper = getWrapper();
        wrapper.in("department_id", departmentIds);

        mapper.update(po, wrapper);
    }

    /**
     * 获取企业下所有角色的id
     *
     * @param tenantId
     * @return
     */
    @Override
    public List<Long> getRoleIdListByTenantId(Long tenantId) {
        return mapper.getRoleIdListByTenantId(tenantId);
    }

    /**
     * 批量获取用户下的角色
     *
     * @param userIds
     * @return
     */
    @Override
    public Map<Long, List<UserRoleDto>> getRoleListByUserIds(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Collections.EMPTY_MAP;
        }

        return mapper.getRoleListByUserIds(userIds)
                .stream()
                .collect(Collectors.groupingBy(UserRoleDto::getUserId));
    }

    /**
     * 批量获取角色下的用户
     * @param roleIds
     * @return
     */
    @Override
    public Map<Long, List<UserRoleDto>> getUserListByRoleIds(List<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return Collections.EMPTY_MAP;
        }

        return mapper.getUserListByRoleIds(roleIds)
                .stream()
                .collect(Collectors.groupingBy(UserRoleDto::getRoleId));
    }

}